package com.bootdo.web.service;

import com.bootdo.common.utils.JsonData;
import com.bootdo.entity.PurchaseApply;
import com.bootdo.web.dao.PurchaseApplyMapper;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author wukq
 * @Date: 2020/7/20 18:22
 * @Description:
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PurchaseServiceImpl implements PurchaseService {

  @Resource
  private PurchaseApplyMapper purchaseApplyMapper;
  @Autowired
  private IdentityService identityService;//组织机构管理
  @Autowired
  private RuntimeService runtimeService;//执行管理，包括启动、推进、删除流程实例等操作
  @Autowired
  private TaskService taskService;//任务管理

  /**
   * 开启审批
   * businessKey 是我们表关联流程引擎的key
   */
  public ProcessInstance startWorkflow(PurchaseApply purchase, String userId, Map<String, Object> variables) {
    int i = purchaseApplyMapper.save(purchase);
    if (i != 1) {
      return null;
    }
    int businessKey = purchase.getId();
    identityService.setAuthenticatedUserId(userId);
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("purchase", String.valueOf(businessKey), variables);
    return processInstance;
  }

  /**
   * 根据采购id获取采购
   */
  public PurchaseApply getPurchase(int id) {
    return purchaseApplyMapper.getPurchaseApply(id);
  }

  /**
   * 更新purchase
   */
  public JsonData updatePurchase(PurchaseApply purchase) {
    int i = purchaseApplyMapper.updatePurchaseByParams(purchase);
    if (i != 1) {
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      return JsonData.returnJsonDataError();
    }
    return JsonData.returnJsonDataOK();
  }
}
